<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>reviews页面</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- 引入 toastr 插件的 CSS 文件 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
    <!-- 引入 toastr 插件的 JavaScript 文件 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
    <style>
        img {
            max-width: 100%;
            max-height: 100%;
        }

        button {
            background-color: #007bff;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        button:hover {
            background-color: #0056b3;
        }

        table {
            border-collapse: collapse;
            width: 100%;
        }

        table,
        th,
        td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }

        .header-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .review-section {
            margin-top: 20px;
        }

        .review-box {
            border: 1px solid #ddd;
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 5px;
            position: relative;
        }

        .delete-btn {
            background-color: #dc3545;
        }

        .delete-btn:hover {
            background-color: #c82333;
        }

        .update-btn {
            background-color: #007bff;
        }

        .update-btn:hover {
            background-color: #0056b3;
        }

        textarea#reviewContent {
            width: 100%;
            height: 150px;
        }

        .review-id {
            position: absolute;
            top: 5px;
            right: 5px;
            font-size: 12px;
            color: #999;
        }

        dialog {
            width: 500px;
            padding: 20px;
            border: none;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
        }

        dialog::backdrop {
            background-color: rgba(0, 0, 0, 0.5);
        }

    </style>
</head>

<body>
<div class="header-row">
    <p id="userIdDisplay">用户 ID: </p>
    <button id="backToWelcomeBtn">返回欢迎页面</button>
</div>
<h1>商品评价</h1>
<div id="productInfo">
    <table id="productTable">
        <thead>
        <tr>
            <th>商品 ID</th>
            <th>商品名称</th>
            <th>商品描述</th>
            <th>商品价格</th>
            <th>商品图片</th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td id="productIdCell"></td>
            <td id="productName"></td>
            <td id="productDescription"></td>
            <td id="productPrice"></td>
            <td id="productImageCell"></td>
        </tr>
        </tbody>
    </table>
</div>
<div class="review-section">
    <h2>发表评论</h2>
    <textarea id="reviewContent" rows="4" cols="50" placeholder="请输入评论内容"></textarea>
    <br>
    <button id="submitReviewBtn">提交评论</button>
</div>
<div id="reviewsList">
    <h2>商品评论列表</h2>
    <div id="reviewsContainer"></div>
</div>

<!-- 新增的修改评论对话框 -->
<dialog id="updateReviewDialog">
    <h2>修改评论</h2>
    <textarea id="updateReviewContent" rows="10" cols="50"></textarea>
    <br>
    <button id="saveUpdateBtn">保存修改</button>
    <button id="cancelUpdateBtn">取消</button>
</dialog>

<script>
    // 获取 URL 中的参数
    function getUrlParameter(name) {
        name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
        var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
        var results = regex.exec(location.search);
        return results === null? '' : decodeURIComponent(results[1].replace(/\+/g,''));
    }

    // 获取 productId 参数
    const productId = getUrlParameter('productId');

    // 在页面上展示 productId
    const productIdCell = document.getElementById('productIdCell');
    productIdCell.textContent += productId;

    // 获取 Cookie 中的 JWT Token
    function getCookie(name) {
        const value = `; ${document.cookie}`;
        const parts = value.split(`; ${name}=`);
        if (parts.length === 2) return parts.pop().split(';').shift();
    }

    const token = getCookie('jwtToken');
    let userId;

    if (token) {
        // 发起请求获取用户 ID 和角色
        $.ajax({
            url: '/ReviewsController/getRoleAndUserId',
            type: 'GET',
            headers: {
                'Authorization': `Bearer ${token}`
            },
            success: function (data) {
                if (data) {
                    const userIdDisplay = document.getElementById('userIdDisplay');
                    userIdDisplay.textContent += data.id;
                    userId = data.id;
                } else {
                    toastr.error('未获取到有效的用户信息');
                    console.error('未获取到有效的用户信息');
                }
            },
            error: function (error) {
                toastr.error('请求出错: ' + error.statusText);
                console.error('请求出错:', error);
            }
        });
    } else {
        toastr.error('未找到 JWT Token');
        console.error('未找到 JWT Token');
    }

    // 发起请求获取商品信息
    if (productId) {
        $.ajax({
            url: `/ReviewsController/getProduct?productId=${productId}`,
            type: 'GET',
            success: function (product) {
                if (product) {
                    const productName = document.getElementById('productName');
                    productName.textContent += product.product_name;

                    const productDescription = document.getElementById('productDescription');
                    productDescription.textContent += product.description;

                    const productPrice = document.getElementById('productPrice');
                    productPrice.textContent += product.price;

                    const productImageCell = document.getElementById('productImageCell');
                    const productImage = document.createElement('img');
                    productImage.src = product.image_url;
                    productImage.width = 100; // 设置图片宽度，和商品列表页类似
                    productImageCell.appendChild(productImage);
                } else {
                    toastr.error('未获取到有效的商品信息');
                    console.error('未获取到有效的商品信息');
                }
            },
            error: function (error) {
                toastr.error('请求商品信息出错: ' + error.statusText);
                console.error('请求商品信息出错:', error);
            }
        });
    }

    // 格式化日期
    function formatDate(dateStr) {
        const date = new Date(dateStr);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }

    // 在 $(document).ready 函数中添加获取评论列表的代码
    $(document).ready(function () {
        $('#backToWelcomeBtn').click(function () {
            window.location.href = 'welcome.html';
        });

        // 为提交评论按钮绑定点击事件
        $('#submitReviewBtn').click(function () {
            const reviewContent = $('#reviewContent').val();
            if (!userId) {
                toastr.error('未获取到有效的用户 ID，无法提交评论');
                return;
            }
            if (!reviewContent) {
                toastr.error('请输入评论内容');
                return;
            }
            $.ajax({
                url: '/ReviewsController/addReviews',
                type: 'POST',
                contentType: 'application/json', // 设置请求头为 JSON 格式
                headers: {
                    'Authorization': `Bearer ${token}`
                },
                data: JSON.stringify({ // 将数据转换为 JSON 字符串
                    userId: userId,
                    productId: productId,
                    reviewContent: reviewContent
                }),
                success: function (response) {
                    toastr.success('评论提交成功');
                    $('#reviewContent').val('');
                    // 提交成功后重新获取评论列表
                    getReviewsList();
                },
                error: function (error) {
                    toastr.error('提交评论出错: ' + error.statusText);
                    console.error('提交评论出错:', error);
                }
            });
        });

        // 获取评论列表的函数
        function getReviewsList() {
            if (productId) {
                $.ajax({
                    url: `/ReviewsController/getProductReviewsList?productId=${productId}`,
                    type: 'GET',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    },
                    success: function (reviews) {
                        const reviewsContainer = $('#reviewsContainer');
                        reviewsContainer.empty(); // 清空现有评论列表
                        if (reviews.length > 0) {
                            reviews.forEach(function (review) {
                                const reviewBox = $('<div class="review-box"></div>');
                                const userIdText = $('<p>用户 ID:'+ review.userId + '</p>');
                                const reviewContentText = $('<p>评论内容:'+ review.reviewContent + '</p>');
                                const reviewDate = formatDate(review.createdAt);
                                const reviewDateText = $('<p>评论时间:'+ reviewDate + '</p>');
                                const reviewIdText = $('<span class="review-id">评论 ID:'+ review.reviewId + '</span>');

                                reviewBox.append(reviewIdText, userIdText, reviewContentText, reviewDateText);

                                if (userId && review.userId === userId) {
                                    const deleteBtn = $('<button class="delete-btn">删除评论</button>');
                                    const updateBtn = $('<button class="update-btn">修改评论</button>');

                                    deleteBtn.click(function () {
                                        // 修正接口 URL
                                        $.ajax({
                                            url: `/ReviewsController/deleteReviews?reviewId=${review.reviewId}`,
                                            type: 'DELETE',
                                            headers: {
                                                'Authorization': `Bearer ${token}`
                                            },
                                            success: function (response) {
                                                if (response.success) {
                                                    toastr.success('评论删除成功');
                                                } else {
                                                    toastr.error(response.message);
                                                }
                                                getReviewsList();
                                            },
                                            error: function (error) {
                                                toastr.error('删除评论出错:'+ error.statusText);
                                                console.error('删除评论出错:', error);
                                            }
                                        });
                                    });

                                    updateBtn.click(function () {
                                        const dialog = document.getElementById('updateReviewDialog');
                                        const updateReviewContent = document.getElementById('updateReviewContent');
                                        updateReviewContent.value = review.reviewContent;
                                        dialog.reviewId = review.reviewId;
                                        dialog.showModal();
                                    });

                                    reviewBox.append(deleteBtn, updateBtn);
                                }

                                reviewsContainer.append(reviewBox);
                            });
                        } else {
                            const noReviewsItem = $('<p>暂无评论</p>');
                            reviewsContainer.append(noReviewsItem);
                        }
                    },
                    error: function (error) {
                        toastr.error('获取评论列表出错: '+ error.statusText);
                        console.error('获取评论列表出错:', error);
                    }
                });
            }
        }

        // 页面加载时获取评论列表
        getReviewsList();

        // 保存修改按钮点击事件
        $('#saveUpdateBtn').click(function () {
            const dialog = document.getElementById('updateReviewDialog');
            const reviewId = dialog.reviewId;
            const newContent = $('#updateReviewContent').val();
            if (newContent!== null) {
                $.ajax({
                    url: `/ReviewsController/updateReviews`,
                    type: 'PUT',
                    contentType: 'application/json',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    },
                    data: JSON.stringify({
                        reviewId: reviewId,
                        reviewContent: newContent
                    }),
                    success: function (response) {
                        if (response.success) {
                            toastr.success('评论修改成功');
                        } else {
                            toastr.error(response.message);
                        }
                        getReviewsList();
                        dialog.close();
                    },
                    error: function (error) {
                        toastr.error('修改评论出错:'+ error.statusText);
                        console.error('修改评论出错:', error);
                        dialog.close();
                    }
                });
            }
        });

        // 取消按钮点击事件
        $('#cancelUpdateBtn').click(function () {
            const dialog = document.getElementById('updateReviewDialog');
            dialog.close();
        });
    });
</script>
</body>

</html>